package com.ailanyin.admin.service.impl;


import com.ailanyin.admin.service.SysPermissionService;
import com.ailanyin.admin.service.SysUserService;
import com.ailanyin.admin.vo.LoginUser;
import com.ailanyin.common.enums.UserEnum;
import com.ailanyin.common.exception.Asserts;
import com.ailanyin.common.utils.StringUtil;
import com.ailanyin.model.SysUser;
import com.ailanyin.security.service.SecurityUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService userService;
    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private SecurityUserService securityUserService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        if (securityUserService.getUserDetailsFromMap(username) != null) {
            return securityUserService.getUserDetailsFromMap(username);
        }

        SysUser user = userService.selectUserByUserName(username);
        if (StringUtil.isNull(user)) {
            Asserts.fail("登录用户：" + username + " 不存在");
        } else if (UserEnum.DELETED.getCode().equals(user.getDelFlag())) {
            Asserts.fail("对不起，您的账号：" + username + " 已被删除");
        } else if (UserEnum.DISABLE.getCode().equals(user.getStatus())) {
            Asserts.fail("对不起，您的账号：" + username + " 已停用");
        }
        UserDetails userDetails = createUserDetails(user);
        securityUserService.addUserDetailsToMap(username,userDetails);
        return userDetails;
    }

    private UserDetails createUserDetails(SysUser user) {
        return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
    }

}
